package test.domain;

import org.omg.CORBA.PUBLIC_MEMBER;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : example
 * @ Author: XuLeHuang
 * @ Date: 2022/10/29 21:38
 * @ Description:
 */
public class FileUpload extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter out = response.getWriter();
        //out.write(request.getServerName());
        response.setCharacterEncoding(new String("UTF-8"));
        String fileSerialNumber = request.getParameter("file-serial-number");
        if (fileSerialNumber != null) {
            response.setHeader("Content-Type", "application/javascript");
            //writeState(out, fileSerialNumber);
            return;
        }

        String pathKey = request.getParameter("path-key");
        if (pathKey == null) {
            return;
        }

        String editor = request.getParameter("editor");


    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) {

        byte[] buffer = new byte[1024 * 1024];
        int readLength;
        int fileNameIndex;
        String readString;
        String fileName = "";
        String fileEndFlag = "";
        String physicalFullPath = "";

        /*UploadingProgress status;
        AttachUploadParam attachUploadBo;*/
        try {
            this.assembleFileInfo(request);
            //status = this.expirableStatusCache.get(attachUploadBo.getFileSerialNumber());
        } catch (IOException ignore) {
            return;
        }

        /*String pathKey = attachUploadBo.getPathKey();
        String editor = attachUploadBo.getEditor();
        FileConfig fileConfig = this.configAssemble.assemble(pathKey);
        int fileConfigLength = fileConfig
                .getLength();
        if (request.getContentLength() > fileConfigLength) {
            status.setError(SparrowError.UPLOAD_OUT_OF_SIZE.getMessage());
            this.uploadEnd(status, pathKey, editor, response);
            return;
        }

        attachUploadBo.setCreateUserId(loginToken.getUserId());
        FileOutputStream fileOutputStream = null;
        ServletInputStream servletInputStream = null;
        try {
            servletInputStream = request.getInputStream();
            while ((readLength = servletInputStream.readLine(buffer,
                    0, buffer.length)) != -1) {
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                status.setReadLength(status.getReadLength()
                        + readLength);
                readString = new String(buffer, 0, readLength,
                        StandardCharsets.UTF_8);

                if (StringUtility.isNullOrEmpty(fileEndFlag)) {
                    // -----------------------------7da3992a803bc--为文件头结尾标记
                    fileEndFlag = readString.substring(0,
                            readLength - 2)
                            + "--"
                            + readString.substring(readLength - 2);
                    continue;
                }
                fileNameIndex = readString
                        .indexOf("\"; filename=\"");
                if (fileNameIndex != -1
                        && StringUtility.isNullOrEmpty(fileName)) {
                    // Content-Disposition: form-data;
                    // name="file_upload"
                    // filename="上传的文件名.扩展名"
                    fileName = readString.substring(
                            fileNameIndex + 13,
                            readString.length() - 3);
                    if (StringUtility.isNullOrEmpty(fileName)) {
                        status.setError(SparrowError.UPLOAD_FILE_NAME_NULL.getMessage());
                        this.uploadEnd(status, pathKey, editor, response);
                        return;
                    }
                    attachUploadBo.setClientFileName(fileName
                            .substring(fileName.lastIndexOf('\\') + 1));
                    status.setClientFileName(attachUploadBo.getClientFileName());

                    String rightFileType = ConfigUtility
                            .getValue(com.sparrow.constant.File.RIGHT_TYPE
                                    + "_" + pathKey.toLowerCase());
                    if (rightFileType != null
                            && !rightFileType.toLowerCase().contains(FileUtility.getInstance()
                            .getFileNameProperty(fileName).getExtension()
                            .toLowerCase())) {
                        status.setContentType(com.sparrow.constant.File.ERROR_TYPE + "|"
                                + rightFileType);
                        status.setError(SparrowError.UPLOAD_FILE_TYPE_ERROR.getMessage());
                        this.uploadEnd(status, pathKey, editor, response);
                        return;
                    }
                    continue;
                }

                if (readString.contains("Content-Type")
                        && StringUtility.isNullOrEmpty(status.getContentType())) {
                    // Content-Type: application/msword
                    readLength = servletInputStream.readLine(buffer,
                            0, buffer.length);
                    status.setContentType(readString.split(":")[1]
                            .trim());
                    status.setReadLength(status
                            .getReadLength() + readLength);

                    attachUploadBo.setContentType(status.getContentType());
                    physicalFullPath = this.assembleFileName(attachUploadBo, fileConfig, loginToken);
                    File file = new File(physicalFullPath.substring(0,
                            physicalFullPath.lastIndexOf("/") + 1));
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    fileOutputStream = new FileOutputStream(
                            physicalFullPath);
                    continue;
                }
                // 如果是文件的结尾
                if (fileEndFlag.equals(readString)) {
                    continue;
                }
                fileOutputStream.write(buffer, 0, readLength);
            }
        } catch (IOException e) {
            logger.error("make thumbnail", e);
            status.setError(SparrowError.UPLOAD_SERVICE_ERROR.getMessage());
            this.uploadEnd(status, pathKey, editor, response);
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    servletInputStream.close();
                } catch (IOException e) {
                    status.setError(SparrowError.UPLOAD_SERVICE_ERROR.getMessage());
                    this.uploadEnd(status, pathKey, editor, response);
                }
            }
        }
        if (!attachUploadBo.isImage() || !fileConfig.isDeal()) {
            this.uploadEnd(status, pathKey, editor, response);
            return;
        }

        UploadPostProcessStrategy uploadPostProcessStrategy = ApplicationContext.getContainer().getBean("uploadPostProcessStrategy");
        uploadPostProcessStrategy.uploadPostProcessing(physicalFullPath, attachUploadBo, fileConfig);
        this.uploadEnd(status, pathKey, editor, response);*/
    }

    private void assembleFileInfo(HttpServletRequest request) throws IOException {

         /*   UploadingProgress status = new UploadingProgress();*/
             ServletInputStream servletInputStream = request.getInputStream();
            byte[] buffer = new byte[1024 * 1024];
        int readLength = 0;

        /*while (true) {
            readLength = servletInputStream
                    .readLine(buffer, 0, buffer.length);
            if (readLength == 0 ){
                break;
            }
            String fileInfo = new String(buffer, 0, readLength - 2 , StandardCharsets.UTF_8);
            System.out.println(fileInfo);
        }*/
            for (int i = 0; i < 10; i++) {
                readLength = servletInputStream
                        .readLine(buffer, 0, buffer.length);
                String fileInfo = new String(buffer, 0, readLength - 2 , StandardCharsets.UTF_8);
                System.out.println(fileInfo);
            }
            readLength = servletInputStream.readLine(buffer, 0, buffer.length);
            String fileInfo = new String(buffer, 0, readLength - 2, StandardCharsets.UTF_8);
        System.out.println(fileInfo);
            String[] fileInfoArray = fileInfo.split("\\.");
            String editor = new String(fileInfoArray[0].getBytes() , StandardCharsets.UTF_8);
            String pathKey = fileInfoArray[1];
            String fileSerialNumber = fileInfoArray[2];
   /*         status.setReadLength((long) readLength);
            status.setContentLength((long) request.getContentLength());
            this.expirableStatusCache.put(fileSerialNumber, status);
            AttachUploadParam attachUploadBo = new AttachUploadParam();
            attachUploadBo.setFileSerialNumber(fileSerialNumber);
            attachUploadBo.setPathKey(pathKey);
            attachUploadBo.setEditor(editor);
            attachUploadBo.setContentType(status.getContentType());
            attachUploadBo.setContentLength(status.getContentLength());*/

    }

  /*  public void initUploadHtml(PrintWriter out, String pathKey , String editor) {
        String fileInfo = editor + "." + pathKey + "." + "123";
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<html>");
        out.println("<head><title>文件上传 -" + "</title>");
        out.println("<script type=\"text/javascript\">");
        //跨域必须两端都加
        out.println(String.format("window.onload=function(){document.domain=window.location.host.substr(window.location.host.indexOf('.')+1);if(!parent.$){return;}if(parent.$.file.uploadCallBack){parent.$.file.uploadCallBack(%s,%s,%s);}}", json.toString(progress),
                "null".equals(editor) ? "null" : "parent." + editor, "455"));
        out.println("</script>");
        out.println("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">");
        out.println("</head>");
        out.println("<body style='margin:0px;padding:0px;height:25px;'>");
        out.println("<form action=\"file-upload\" method=\"post\" enctype=\"multipart/form-data\" target=\"_self\">");
        out.println("<input type=\"hidden\" id=\"fileInfo\" name=\"fileInfo\" value=\""
                + fileInfo + "\" />");
        out.println("<input style=\"cursor:pointer;width:200px;\" type=\"file\" id=\"file_upload\" name=\"file_upload\"");
        out.println(String.format(" onchange=\"parent.$.file.validateUploadFile(this,'%s',%s);\" />", pathKey, ("null".equals(editor) ? "" : "parent." + editor)));
        out.println("</form>");
        out.println("  </body>");
        out.println("</html>");
    }*/
}
